package com.situ.stmall.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.stmall.entity.Goods;
import com.situ.stmall.entity.Shopcart;
import com.situ.stmall.mapper.GoodsMapper;
import com.situ.stmall.mapper.ShopcartMapper;
import com.situ.stmall.service.ShopcartService;

@Service
public class ShopcartServiceImpl implements ShopcartService{

	@Autowired
	private ShopcartMapper shopcartMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	
	@Override
	public int add(Shopcart shopcart) {
		//查找有没有对应的购物车信息
		Shopcart selectCart = shopcartMapper.select(shopcart);
		if (selectCart != null) {
			//
			selectCart.setCount(selectCart.getCount()+1);
			//更新数据库
			return shopcartMapper.updateByPrimaryKey(selectCart);
		}else {
			return shopcartMapper.insert(shopcart);
		}
		
	}
	@Override
	public List getByUserId(Integer userId) {
		//根据用户ID查询当前用户购物车信息
		List<Shopcart> carts = shopcartMapper.selectByUserId(userId);
		
		//遍历所有购物车信息
		for (Shopcart cart : carts) {
			if (cart.getCount() >cart.getGoods().getCount()) {
				cart.setCount(cart.getGoods().getCount());
				shopcartMapper.updateByPrimaryKey(cart);
			}
		}
		
		return carts;
	}
	@Override
	public Shopcart update(Shopcart cart) {
		//验证商品数量信息，获取商品的信息
		
		Shopcart selectCart = shopcartMapper.selectByPrimaryKey(cart.getId());
		
		//查询商品信息
		Goods goods = goodsMapper.selectByPrimaryKey(selectCart.getGoodsId());
		
		if (goods.getCount() < cart.getCount()) {
			selectCart.setCount(goods.getCount());
			shopcartMapper.updateByPrimaryKey(selectCart);
		}else {
			shopcartMapper.updateByPrimaryKey(cart);
		}
		return shopcartMapper.selectByPrimaryKey(cart.getId());
	}
	@Override
	public Shopcart removeById(Integer id) {
		Shopcart cart = shopcartMapper.selectByPrimaryKey(id);
		int res = shopcartMapper.deleteByPrimaryKey(id);
		return cart;
	}

}
